import { useState, useEffect } from 'react'
import { ChatInterface } from '@/components/ChatInterface'
import { ChatService } from '@/services/chatService'
import { ChatMessage } from '@/services/chatService'

export function ChatApp() {
  const [messages, setMessages] = useState<ChatMessage[]>([])
  const [inputMessage, setInputMessage] = useState('')
  const [isLoading, setIsLoading] = useState(false)
  const [conversationId, setConversationId] = useState<string>()
  const [userId] = useState<string>('1') // 默认用户ID，实际应用中应该从认证系统获取
  const [isAgentMode, setIsAgentMode] = useState(false)

  const chatService = ChatService.getInstance()

  // 加载对话历史（如果有conversationId）
  useEffect(() => {
    if (conversationId && conversationId !== 'unknown') {
      loadConversationHistory()
    }
  }, [conversationId])

  const loadConversationHistory = async () => {
    if (!conversationId || conversationId === 'unknown') return
    
    try {
      const history = await chatService.getConversationHistoryFromDB(parseInt(conversationId))
      const chatMessages: ChatMessage[] = history.map(msg => ({
        id: msg.id.toString(),
        content: msg.content,
        role: msg.role as 'user' | 'assistant',
        timestamp: new Date(msg.created_at)
      }))
      setMessages(chatMessages)
    } catch (error) {
      console.error('Error loading conversation history:', error)
    }
  }

  const handleSendMessage = async () => {
    if (!inputMessage.trim() || isLoading) return

    const userMessage: ChatMessage = {
      id: Date.now().toString(),
      content: inputMessage,
      role: 'user',
      timestamp: new Date()
    }

    setMessages(prev => [...prev, userMessage])
    const currentMessage = inputMessage
    setInputMessage('')
    setIsLoading(true)

    try {
      // 根据模式选择不同的API
      const { stream, conversationId: newConversationId } = isAgentMode 
        ? await chatService.sendAgentMessage(currentMessage, conversationId, userId)
        : await chatService.sendMessageWithMemory(currentMessage, conversationId, userId)
      
      // 更新conversationId（如果是新对话）
      if (!conversationId && newConversationId !== 'unknown') {
        setConversationId(newConversationId)
      }
      
      let assistantContent = ''
      let messageId = Date.now().toString()

      // 先创建一个空的assistant消息，然后逐步更新内容
      const assistantMessage: ChatMessage = {
        id: messageId,
        content: '',
        role: 'assistant',
        timestamp: new Date(),
        isStreaming: true
      }
      
      setMessages(prev => [...prev, assistantMessage])

      for await (const chunk of stream) {
        // 直接处理文本内容
        assistantContent += chunk
        
        // 实时更新消息内容
        setMessages(prev => 
          prev.map(msg => 
            msg.id === messageId 
              ? { ...msg, content: assistantContent, isStreaming: true }
              : msg
          )
        )
      }
      
      // 流式传输完成，移除 isStreaming 标志
      setMessages(prev => 
        prev.map(msg => 
          msg.id === messageId 
            ? { ...msg, isStreaming: false }
            : msg
        )
      )
    } catch (error) {
      console.error('Error sending message:', error)
      const errorMessage: ChatMessage = {
        id: Date.now().toString(),
        content: 'Sorry, there was an error processing your message. Please try again.',
        role: 'assistant',
        timestamp: new Date()
      }
      setMessages(prev => [...prev, errorMessage])
    } finally {
      setIsLoading(false)
    }
  }

  const handleToggleAgentMode = (enabled: boolean) => {
    setIsAgentMode(enabled)
    // 可以选择在切换模式时清空对话历史
    // setMessages([])
    // setConversationId(undefined)
  }
  
  return (
    <ChatInterface
      messages={messages}
      inputMessage={inputMessage}
      setInputMessage={setInputMessage}
      onSendMessage={handleSendMessage}
      isLoading={isLoading}
      conversationId={conversationId}
      isAgentMode={isAgentMode}
      onToggleAgentMode={handleToggleAgentMode}
    />
  )
}